<?php
/**
 * @name /lib/private/ItemSearchWidget.php
 * @author Michael Foss <michael@mikefoss.com>
 * @version 2011.04.02
 *
 * A widget to search for items.
 */

ReqLib('/lib/private/User.php');
ReqLib('/lib/private/Item.php');

/**
 * ItemSearchWidget class.
 *
 */
class ItemSearchWidget {
  /**
   * The unique id of the widget.
   *
   * @var integer
   */
  var $Id;
  /**
   * A list of tags that are already pre-selected.
   *
   * @var string[]
   */
  var $SelectedTags;
  /**
   * The default string to display in the query text box.
   *
   * @var string
   */
  var $Query;
  /**
   * Where to take the search (in case it's different that the current page).
   *
   * @var string
   */
  var $FormAction;
  /**
   * Whether or not to filter by verified items (-1 for both).
   *
   * @var fuzzy boolean
   */
  var $IsVerified;
  /**
   * Whether or not form submission is enabled;
   * if false, will not allow form to submit
   * and will remove the Search button.
   *
   * @var boolean
   */
  var $SubmitEnabled;

  /**
   *
   * Constructor.
   *
   */
  function ItemSearchWidget() {
    $this->Id = 'ItemSearchWidget';
    $this->SelectedTags = (isset($_GET['t']) ? explode('|', $_GET['t']) : array());
    $this->Query = (isset($_GET['q']) ? $_GET['q'] : '');
    $this->FormAction = '';
    $this->SubmitEnabled = true;
    switch ($_GET['v']) {
      case 'B':
        $this->IsVerified = -1;
        break;
      case 'N':
        $this->IsVerified = false;
        break;
      default:
        $this->IsVerified = true;
        break;
    }
  }

  /**
   * Displays an item search widget; uses /www/itemsearch-widget-ajax.php.
   *
   * @static
   */
  function DisplayWidget() {
?>
<div class="ItemSearchWidget ui-widget" id="<?=htmlspecialchars($this->Id) ?>">
  <form action="<?=$this->FormAction ?>" method="GET"<?=$this->SubmitDisabled ? ' onsubmit="return false;"' : '' ?>>
    <div class="ItemSearchWidget_Tags">
      <select multiple="multiple" title="Search Only..." class="ItemSearchWidget_TagsSelect UnSelectListed">
<?
    $tags = Item::GetTags();
    for ($i = 0; $i < count($tags); $i++)
      $tags[$i] = '<option value="' . htmlspecialchars($tags[$i]) . '"' . (in_array($tags[$i], $this->SelectedTags) ? ' selected="selected"' : '') . '>' . htmlspecialchars($tags[$i]) . '</option>';
    println(implode($tags));
?>
      </select>
<?
    $user = new User();
    $user->Load($_SESSION['userId']);
    if ($user->HasRole('administrator')) {
?>
      <div>
        Verified Items:<br />
        <select name="v">
          <option value="B"<?=$_GET['v'] == 'B' ? ' selected="selected"' : '' ?>>Both</option>
          <option value="V"<?=$_GET['v'] == 'V' ? ' selected="selected"' : '' ?>>Verified Only</option>
          <option value="N"<?=$_GET['v'] == 'N' ? ' selected="selected"' : '' ?>>Not Verified</option>
        </select>
      </div>
<?
    }
?>
    </div>
    <div class="ItemSearchWidget_Query">
      Search:<br />
      <input type="text" name="q" class="ItemSearchWidget_QueryTextBox ac_Input" value="<?=htmlspecialchars($this->Query) ?>" /><br />
      <?=$this->SubmitEnabled ? '<input type="submit" value="Search" />' : '' ?>
    </div>
    <div class="Clear">&nbsp;</div>
    <input type="hidden" class="ItemSearchWidget_TagsHidden" name="t" value="" />
  </form>
</div>
<script type="text/javascript">
  $(function() {
    var id = '#<?=str_replace("'", "\\'", $this->Id) ?>';
    var $itemSearchWidget = $(id);
    var $textBox = $itemSearchWidget.find('.ItemSearchWidget_QueryTextBox');
    $itemSearchWidget.find('input[type=submit]').button();
    $('.ItemSearchWidget_QueryTextBox').autocomplete({
      source: function(req, add) {
        var tags = '';
        $.each($itemSearchWidget.find('select:eq(0) option'), function(i, opt) {
          tags += (i ? '|' : '') + opt.value;
        });
        req.tags = tags;
        req.v = $('.ItemSearchWidget select[name=v]').val();
        $.post(
          '<?=_webroot('/itemsearch-widget-ajax.php') ?>',
          req,
          function(data) {
            var suggestions = [];
            for (i = 0; i < data.length; i++)
              suggestions[i] = data[i];
            add(suggestions);
          },
          'json'
        );
      }
    });
    // We have to use an UnSelectListed class as an identifier
    // to make sure we're not having this called multiple times;
    // seems to be a bug when working within multi-dialogs
    $('.ItemSearchWidget_TagsSelect.UnSelectListed')
      .removeClass('UnSelectListed')
      .selectList({
        onAdd: function(select, value, text) {
          var tags = '';
          $.each($('.ItemSearchWidget_TagsSelect:eq(0) option'), function(i, tag) {
            tags += (i ? '|' : '') + tag.value;
          });
          $.post(
            '<?=_webroot('/itemsearch-widget-ajax.php') ?>',
            {
              't': tags
            },
            function(data) {
              autocompleteData = data;
            },
            'json'
          );
        },
        onRemove: function(select, value, text) {
          var tags = '';
          $.each($('.ItemSearchWidget_TagsSelect:eq(0) option'), function(i, tag) {
            tags += (i ? '|' : '') + tag.value;
          });
          $.post(
            '<?=_webroot('/itemsearch-widget-ajax.php') ?>',
            {
              't': tags
            },
            function(data) {
              autocompleteData = data;
            },
            'json'
          );
        }
      });
      // clearSearch()
      $itemSearchWidget.data('clearSearch', function() {
        var $itemSearchWidgetTagsSelect = $itemSearchWidget.find('select.ItemSearchWidget_TagsSelect:eq(0)');
        console.log('clearSearch()');
        var tags = $itemSearchWidgetTagsSelect.val();
        if (tags)
          for (i = 0; i < tags.length; i++)
            $itemSearchWidgetTagsSelect.remove(tags[i]);
        $itemSearchWidget.data('val')('');
        return $itemSearchWidget;
      });
      // new val()
      $itemSearchWidget.data('val', function(newQuery) {
        $query = $itemSearchWidget.find('input.ItemSearchWidget_QueryTextBox');
        if (newQuery === undefined)
          return $query.val();
        else {
          $query.val(newQuery);
          return $itemSearchWidget;
        }
      });
      // getTags()
      $itemSearchWidget.data('getTags', function() {
        return $itemSearchWidget.find('select.ItemSearchWidget_TagsSelect:eq(0)').val();
      });
<?
    // Only bind to form submit if enabled
    if ($this->SubmitEnabled) {
?>
    var $form = $itemSearchWidget.find('form');
    $form.bind('submit', function() {
      var $tagsVar = $form.find('.ItemSearchWidget_TagsHidden');
      var text = '';
      $.each($itemSearchWidget.find('.ItemSearchWidget_TagsSelect:eq(0) option'), function(i, tag) {
        text += (i ? '|' : '') + tag.value;
      });
      $tagsVar.val(text);
      return true;
    });
<?
    }
?>
  });
</script>
<?
  }

  function GetFilteredSearchResults() {
    $items = Item::FilteredSearch($this->Query, $this->SelectedTags, $this->IsVerified);
    return $items;
  }
}
